/**
 * @Author: ls-mac
 * @Date:   2018-10-15T19:40:25+08:00
 * @Last modified by:   ls-mac
 * @Last modified time: 2018-11-13T15:23:30+08:00
 */

import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import moment from 'moment';
import { Row, Col, Card, Form, message, List, Button } from 'antd';

import CheckTagbox from 'components/CheckTagbox';
import PageHeaderLayout from '../../layouts/PageHeaderLayout';
import styles from './Basics.less';
import errorMsg from '../../utils/error';

@connect(({ auth, loading }) => ({
  auth,
  loading: loading.models.auth,
}))
@Form.create()
export default class TableList extends PureComponent {
  state = {
    modalVisible: false,
    expandForm: false,
    selectedRows: [],
    formValues: {},
  };

  componentDidMount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'auth/fetch',
      payload: { userId: this.props.location.userId },
    });
  }

  handleSave = () => {
    const {
      dispatch,
      form,
      auth: { recourseList },
    } = this.props;

    const chooseIdList = [];
    for (const resource of recourseList) {
      if (resource.childNodes && resource.childNodes.length > 0) {
        for (const node of resource.childNodes) {
          if (form.getFieldValue(`parent${  node.resource.resourceId}`))
            chooseIdList.push(node.resource.resourceId);
          const childValues = form.getFieldValue(`child${  node.resource.resourceId}`);
          if (childValues && childValues.length > 0) {
            for (const childId of childValues) {
              chooseIdList.push(childId);
            }
          }
        }
      }
    }

    dispatch({
      type: 'auth/modify',
      payload: {
        userId: this.props.location.userId,
        resourceIds: chooseIdList,
      },
      callback: resp => {
        if (resp && resp.success) {
          message.success('保存成功');
        } else {
          errorMsg(resp);
        }
      },
    });
  };

  render() {
    const {
      auth: { recourseList, userResourceIds },
      loading,
      form,
    } = this.props;

    const dataList = recourseList.map(record => {
      const obj = {};
      obj.title = record.resource.resourceName;

      if (record.childNodes && record.childNodes.length > 0) {
        obj.data = record.childNodes.map(parentRecord => {
          const parentObj = {};
          if (parentRecord.childNodes && parentRecord.childNodes.length > 0) {
            parentObj.options = parentRecord.childNodes.map(childRecord => {
              const childObj = {
                label: childRecord.resource.resourceName,
                value: childRecord.resource.resourceId,
                defaultChecked: false,
              };
              if (userResourceIds && userResourceIds.length > 0) {
                for (const userResouceId of userResourceIds) {
                  if (userResouceId === childRecord.resource.resourceId) {
                    childObj.defaultChecked = true;
                    break;
                  }
                }
              }
              return childObj;
            });
            // parentObj.options = [...parentObj.options,...parentObj.options]
          } else {
            parentObj.options = [];
          }
          parentObj.title = parentRecord.resource.resourceName;
          parentObj.parentIndex = `parent${  parentRecord.resource.resourceId}`;
          parentObj.childIndex = `child${  parentRecord.resource.resourceId}`;
          parentObj.parentValue = parentRecord.resource.resourceId;
          parentObj.defaultChecked = false;
          if (userResourceIds && userResourceIds.length > 0) {
            for (const userResouceId of userResourceIds) {
              if (userResouceId === parentRecord.resource.resourceId) {
                parentObj.defaultChecked = true;
                break;
              }
            }
          }
          return parentObj;
        });
      } else {
        obj.data = [];
      }
      return obj;
    });

    return (
      <PageHeaderLayout title="用户授权">
        <Card bordered={false} loading={loading}>
          <div className={styles.tableList}>
            {dataList.map((record, index) => {
              return (
                <List
                  header={<div style={{ fontWeight: 'bold', color: '#000' }}>{record.title}</div>}
                  bordered
                  dataSource={record.data}
                  key={index}
                  renderItem={item => {
                    const parentProps = {
                      form,
                      options: item.options,
                      dataIndex: item.childIndex,
                      title: item.title,
                      titleIndex: item.parentIndex,
                      parenChecked: item.defaultChecked,
                    };
                    return (
                      <List.Item style={{ width: '100%' }}>
                        <CheckTagbox {...parentProps} />
                      </List.Item>
                    );
                  }}
                />
              );
            })}

            <div className={styles.tableListOperator} style={{ marginTop: 4 }}>
              <Button type="primary" onClick={() => this.handleSave()} loading={loading}>
                &nbsp;&nbsp;保存&nbsp;&nbsp;
              </Button>
            </div>
          </div>
        </Card>
      </PageHeaderLayout>
    );
  }
}
